package student.aistar.day15.Thread02;

/**
 * 线程之间的通信 - 生产者消费者
 *
 * 效果是: 必须是生产者进程先进去执行.
 *      放一个
 *      取一个
 *      放两个
 *      取两个
 *      一次性放, 一次性取
 *      不能连续出现两次放/取
 */
public class ThreadTongXinDemo {
    public static void main(String[] args) {
        Box box = new Box();
        Product product = new Product(box);
        Consumer consumer = new Consumer(box);

        product.setName("生产者");
        consumer.setName("消费者");

        product.start();
        consumer.start();
    }
}
class Box{
    private Integer content;


    private boolean flag;

    public synchronized void setContent(int content){
        if(flag){//为真时, 说明生产者已经有产品了, 需要消费者消费
//            System.out.println("有产品了, 请消费者消费");
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

//        try {
//            Thread.sleep(1000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        //System.out.println(Thread.currentThread().getName() + "生产了: " + (i));
        this.content = content;
        flag = true;
        notifyAll();
    }

    public synchronized int getContent(){
        if(!flag){//当flag为真时, 说明已经有产品了, 不需要走等待,等待了是因为当前消费者没有资源可消费
//            System.out.println("当前");
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

//        try {
//            Thread.sleep(1000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        //生产者有产品, 消费者请消费
        flag = false;
        notifyAll();
        return content;
    }
}
class Product extends Thread{
    private Box box;
    int i;

    public Product(Box box) {
        this.box = box;
    }

    @Override
    public void run() {
        while (true){
            System.out.println(Thread.currentThread().getName() + "->放" + ++i + "个");
            box.setContent(i);
        }
    }
}
class Consumer extends Thread{
    private Box box;

    public Consumer(Box box) {
        this.box = box;
    }

    @Override
    public void run() {
        while (true) {
            System.out.println((Thread.currentThread().getName() + "消费了: " + box.getContent()));
        }
    }
}